package com.yoke.controller.order;

import com.alibaba.druid.util.JdbcUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.common.JsonMessage;
import com.yoke.common.base.NginxBaseControl;
import com.yoke.database.DatabaseContextHolder;
import com.yoke.service.order.KhService;
import com.yoke.service.order.OrderService;
import com.yoke.service.order.ProductService;
import com.yoke.system.log.LogType;
import com.yoke.system.log.SystemLog;
import com.yoke.util.DateUtil;
import com.yoke.util.FileUtil;
import com.yoke.util.JsonUtil;
import com.yoke.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.regex.Pattern;

/**
 * Created by jiangzeyin on 2017/5/18.
 */
@Controller
@RequestMapping("order")
public class EditProductControl extends NginxBaseControl {

    private static final String KH_DEL = "_del";

    @Resource
    private KhService khService;
    @Resource
    private ProductService productService;
    @Resource
    private OrderService orderService;

    /**
     * 创建产品页面
     *
     * @param name
     * @param type
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "create.html", produces = MediaType.TEXT_HTML_VALUE)
    public String create(String name, String type) throws Exception {
        JSONObject jsonObject = orderService.getOrderInfo(type);
        if (jsonObject == null)
            return "redirect:index.html";
        String path = jsonObject.getString("vmPath");
        return "order/" + path;
    }

    @RequestMapping(value = "chang_product_sort", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String chang(String name, String productName, String to) throws IOException {
        name = convertFilePath(name);
        JSONArray jsonArray = productService.getUserProductJson(name);
        if (jsonArray == null)
            return JsonMessage.getString(300, "数据异常");
        ProductService.sort(jsonArray);
        boolean flag = false;
        int count = jsonArray.size();
        for (int i = 0; i < count; i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name_ = jsonObject.getString("name");
            if (name_.equals(productName)) {
                int sort = 0;
                if ("up".endsWith(to)) {
                    if (i == 0)
                        return JsonMessage.getString(405, "已经在最上面啦");
                    sort = jsonArray.getJSONObject(i - 1).getIntValue("sort") - 1;
                } else if ("down".equals(to)) {
                    if (count - 1 == i)
                        return JsonMessage.getString(405, "已经在最底部啦");
                    sort = jsonArray.getJSONObject(i + 1).getIntValue("sort") + 1;
                }
                jsonObject.put("sort", sort);
                flag = true;
            }
        }
        if (!flag)
            return JsonMessage.getString(300, "改变失败");
        File file = productService.getUserProductFile(name);
        JsonUtil.saveJson(file.getPath(), jsonArray);
        return JsonMessage.getString(200, "ok");
    }

    /**
     * 删除产品
     *
     * @param name
     * @param productName
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "del_product.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String del_product(String name, String productName) throws Exception {
        name = convertFilePath(name);
        JSONArray jsonArray = productService.getUserProductJson(name);
        if (jsonArray == null)
            return JsonMessage.getString(300, "数据异常");
        boolean flag = false;
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name_ = jsonObject.getString("name");
            if (name_.equals(productName)) {
                jsonObject.put("name", name_ + KH_DEL);
                jsonObject.put("delTime", DateUtil.getDate());
                flag = true;
            }
        }
        if (!flag)
            return JsonMessage.getString(300, "删除失败，没有对应数据");
        File file = productService.getUserProductFile(name);
        JsonUtil.saveJson(file.getPath(), jsonArray);
        File old = productService.getUserProductFile(name, productName);
        File newFile = new File(old.getParent(), old.getName() + KH_DEL);
        flag = old.renameTo(newFile);
        if (flag)
            return JsonMessage.getString(200, "删除成功");
        return JsonMessage.getString(100, "删除失败");
    }

    @RequestMapping(value = "edit_save.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String create_save(String khName, String title, String name, String products, String fahus, String mark) throws IOException {
        khName = convertFilePath(khName);
        name = convertFilePath(name);
        if (StringUtil.isChinese(name))
            return JsonMessage.getString(400, "产品标识不能包含中文");
        boolean flag = khService.checkKh(userName, khName);
        if (!flag)
            return JsonMessage.getString(400, "请正确使用系统");
        if (StringUtil.IsEmpty(title, 2, 50))
            return JsonMessage.getString(400, "请输入正确的网页标题");
        JSONArray jsonArray = productService.getUserProductJson(khName);
        flag = false;
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name_ = jsonObject.getString("name");
            if (name_.equals(name)) {
                flag = true;
                jsonObject.put("mark", mark);
                break;
            }
        }
        if (!flag)
            return JsonMessage.getString(400, "修改失败，不存在改产品");
        // 验证目录
        File temp = new File(productService.getCustomerFile(), khName + "/" + name);
        if (!temp.exists())
            return JsonMessage.getString(400, "修改失败，不存在改产品,目录");
        // 修改mark
        // 检查产品是否正确
        JSONArray jsonProducts = new JSONArray();
        JSONArray jsonFahus_s = new JSONArray();
        String r = getIn(products, fahus, jsonProducts, jsonFahus_s);
        if (r != null)
            return r;
        try {
            productService.saveUserProduct(khName, jsonArray);
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("保存产品异常", e);
            return JsonMessage.getString(400, "保存产品异常");
        }
        JSONObject jsonObject = productService.getProductInfoJsonObj(khName, name);
        jsonObject.put("title", title);
        jsonObject.put("product", jsonProducts);
        jsonObject.put("fahu", jsonFahus_s);
        File pJson = new File(temp, "product.json");
        JsonUtil.saveJson(pJson.getPath(), jsonObject);
        return JsonMessage.getString(200, "修改成功");
    }

    /**
     * 确定创建产品
     *
     * @param title
     * @param name
     * @param products
     * @param fahus
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "create_save.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String create_save(String khName, String title, String orderType, String name, String products, String fahus, String mark) throws IOException {
        khName = convertFilePath(khName);
        name = convertFilePath(name);
        if (StringUtil.isChinese(name))
            return JsonMessage.getString(400, "产品标识不能包含中文");
        if (!Pattern.matches("^[0-9a-zA-Z_]+$", name))
            return JsonMessage.getString(400, "产品标识只能是数字,字母或者 '_'");
        boolean flag = khService.checkKh(userName, khName);
        if (!flag)
            return JsonMessage.getString(400, "请正确使用系统");
        if (StringUtil.IsEmpty(title, 2, 50))
            return JsonMessage.getString(400, "请输入正确的网页标题");
        JSONArray jsonArray = productService.getUserProductJson(khName);
        if (jsonArray != null)
            for (int i = jsonArray.size() - 1; i >= 0; i--) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String name_ = jsonObject.getString("name");
                if (name_.equals(name))
                    return JsonMessage.getString(400, "已经存在相同的产品标识");
                if (name_.equals(name + KH_DEL))
                    return JsonMessage.getString(400, "此产品标识已经被使用过，现已被删除");
            }
        JSONObject orderInfo = orderService.getOrderInfo(orderType);
        if (orderInfo == null)
            return JsonMessage.getString(400, "使用错误，请检查");
        // 验证目录
        File productDir = new File(productService.getCustomerFile(), khName + "/" + name);
        if (productDir.exists())
            return JsonMessage.getString(400, "该产品标识已被占用");
        File checkZm = new File(productService.getCustomerFile(), khName);
        String finalName = name;
        String[] xiangTongFile = checkZm.list((dir, fileName) -> fileName.equalsIgnoreCase(finalName) ||
                fileName.equalsIgnoreCase(finalName + KH_DEL));
        if (xiangTongFile != null && xiangTongFile.length > 0)
            return JsonMessage.getString(402, "该产品名称文件已被占用");
        // 检查产品是否正确
        JSONArray jsonProducts = new JSONArray();
        JSONArray jsonFahus_s = new JSONArray();
        String r = getIn(products, fahus, jsonProducts, jsonFahus_s);
        if (r != null)
            return r;
        // 创建对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name", name);
        jsonObject.put("orderType", orderType);
        jsonObject.put("createTime", DateUtil.getDate());
        String tableName = String.format("%s_%s_%s", userName, khName, name).replace('-', '_');
        jsonObject.put("tableName", tableName);
        jsonObject.put("mark", mark);
        if (jsonArray == null)
            jsonArray = new JSONArray();
        jsonArray.add(jsonObject);
        try {
            productService.saveUserProduct(khName, jsonArray);
        } catch (IOException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("保存异常", e);
            return JsonMessage.getString(400, "保存产品异常");
        }
        //File file = productService.getUserProductFile(khName);
        if (!productDir.exists() && !productDir.mkdirs())
            return JsonMessage.getString(405, "文件信息初始化失败，请联系管理员");
        File pJson = new File(productDir, "product.json");
        JSONObject object = new JSONObject();
        object.put("title", title);
        object.put("product", jsonProducts);
        object.put("fahu", jsonFahus_s);
        JsonUtil.saveJson(pJson.getPath(), object);
        File sqlFile = new File(productService.getOrderTypeFile(), String.format("%s.sql", orderType));
        String sql = FileUtil.readToString(sqlFile);
        sql = String.format(sql, tableName);
        DataSource dataSource = DatabaseContextHolder.getDataSource();
        try {
            JdbcUtils.execute(dataSource, sql);
        } catch (SQLException e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("创建失败sql 异常", e);
            return JsonMessage.getString(500, "创建失败，请联系管理员");
        }
        return JsonMessage.getString(200, "创建成功");
    }

    private String getIn(String products, String fahus, JSONArray jsonProducts, JSONArray jsonFahus_s) {
        // 检查产品是否正确
        String[] products_ = StringUtil.StringToArray(products, "\r\n");
        if (products_ == null || products_.length < 1)
            return JsonMessage.getString(400, "请输入产品信息");
        boolean pChecked = false;
        for (String item : products_) {
            String[] item_ = StringUtil.StringToArray(item, ",");
            if (item_ == null || item_.length < 2)
                return JsonMessage.getString(400, "\"" + item + "\",格式不正确");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", item_[0]);
            jsonObject.put("price", StringUtil.parseInt(item_[1]));
            if (item_.length == 3 && !pChecked) {
                jsonObject.put("checked", StringUtil.parseInt(item_[2]) == 1);
                pChecked = true;
            }
            jsonProducts.add(jsonObject);
        }
        // 检查发货单
        String[] fahus_ = StringUtil.StringToArray(fahus, "\r\n");
        if (fahus_ != null && fahus_.length > 0) {

            for (String item : fahus_) {
                String[] item_ = StringUtil.StringToArray(item, ",");
                if (item_ == null || item_.length != 4)
                    return JsonMessage.getString(400, "\"" + item + "\",格式不正确");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("time", item_[0]);
                jsonObject.put("name", item_[1]);
                jsonObject.put("phone", StringUtil.convertNULL(item_[2]));
                jsonObject.put("mark", item_[3]);
                jsonFahus_s.add(jsonObject);
            }
        }
        return null;
    }

    @RequestMapping(value = "edit_product.html", produces = MediaType.TEXT_HTML_VALUE)
    public String edit(String name, String productName) throws Exception {
        name = convertFilePath(name);
        productName = convertFilePath(productName);
        JSONObject jsonObject = productService.getUserProductJsonObj(name, productName);
        if (jsonObject == null)
            return "redirect:index.html";
        String type = jsonObject.getString("orderType");
        JSONObject orderInfo = orderService.getOrderInfo(type);
        if (orderInfo == null)
            return "redirect:index.html";
        String path = orderInfo.getString("vmPath");
        JSONObject item = productService.getProductInfoJsonObj(name, productName);
        JSONArray product = item.getJSONArray("product");
        StringBuffer products = new StringBuffer();
        for (int i = 0; i < product.size(); i++) {
            JSONObject temp = product.getJSONObject(i);
            products.append(temp.getString("name")).append(",").append(temp.getString("price"));
            if (temp.getBooleanValue("checked"))
                products.append(",").append("1");
            products.append("\r\n");
        }
        item.put("product", products);
        JSONArray fahu = item.getJSONArray("fahu");
        StringBuffer fahus = new StringBuffer();
        for (int i = fahu.size() - 1; i >= 0; i--) {
            JSONObject temp = fahu.getJSONObject(i);
            fahus.append(temp.getString("time")).append(",")
                    .append(temp.getString("name")).append(",")
                    .append(temp.getString("phone")).append(",")
                    .append(temp.getString("mark"));
            fahus.append("\r\n");
        }
        item.put("fahu", fahus);
        request.setAttribute("item", item);
        request.setAttribute("itemConf", jsonObject);
        return "order/" + path;
    }
}
